Page({
  data: {
    visitorList: [],
    loading: false,
    residentId: '',
    token: ''
  },

  onLoad() {
    // 获取全局变量
    const app = getApp();
    console.log('全局变量信息:', {
      residentId: app.globalData.residentId,
      userId: app.globalData.userId,
      token: app.globalData.token,
      baseUrl: app.globalData.baseUrl
    });
    
    this.setData({
      residentId: app.globalData.residentId,
      token: app.globalData.token
    });
    
    console.log('页面数据设置:', {
      residentId: this.data.residentId,
      token: this.data.token
    });
    
    // 延迟加载访客记录，确保residentId已设置
    setTimeout(() => {
      this.loadVisitorRecords();
    }, 500);
  },

  onShow() {
    // 页面显示时刷新数据
    const app = getApp();
    console.log('onShow - 重新获取residentId:', app.globalData.residentId);
    
    this.setData({
      residentId: app.globalData.residentId,
      token: app.globalData.token
    });
    
    this.loadVisitorRecords();
  },

  // 加载访客记录
  loadVisitorRecords() {
    console.log('开始加载访客记录...');
    console.log('检查条件:', {
      residentId: this.data.residentId,
      token: this.data.token ? '有token' : '无token'
    });

    if (!this.data.residentId) {
      console.log('缺少residentId');
      wx.showToast({
        title: '缺少住户信息，请重新登录',
        icon: 'none',
        duration: 3000
      });
      return;
    }

    if (!this.data.token) {
      console.log('缺少token');
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 3000
      });
      return;
    }

    console.log('当前住户ID:', this.data.residentId);
    console.log('当前Token:', this.data.token);

    this.setData({ loading: true });

    const app = getApp();
    const baseUrl = app.globalData.baseUrl;

    console.log('请求URL:', `${baseUrl}/property/visitor/list`);
    console.log('请求参数:', { residentId: this.data.residentId });

    wx.request({
      url: `${baseUrl}/property/visitor/list`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + this.data.token
      },
      data: {
        residentId: this.data.residentId
      },
      success: (res) => {
        console.log('访客记录接口返回:', res.data);
        console.log('返回数据详情:', JSON.stringify(res.data, null, 2));
        
        if (res.data.code === 200) {
          const rows = res.data.rows || [];
          console.log('访客记录数量:', rows.length);
          
          if (rows.length > 0) {
            // 处理数据，添加状态文本和样式类
            const visitorList = rows.map(item => {
              console.log('处理访客记录:', item);
              return {
                ...item,
                statusText: this.getStatusText(item.visitStatus),
                statusClass: this.getStatusClass(item.visitStatus),
                date: this.formatDate(item.visitDate),
                duration: this.formatDuration(item.visitDuration)
              };
            });
            
            this.setData({
              visitorList: visitorList
            });
          } else {
            this.setData({
              visitorList: []
            });
            console.log('没有找到访客记录');
            wx.showToast({
              title: '暂无访客记录',
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          wx.showToast({
            title: res.data.msg || '获取访客记录失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取访客记录失败:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 获取状态文本
  getStatusText(status) {
    switch (status) {
      case 1:
        return '生效中';
      case 2:
        return '待生效';
      case 3:
        return '已失效';
      default:
        return '未知状态';
    }
  },

  // 获取状态样式类
  getStatusClass(status) {
    switch (status) {
      case 1:
        return 'status-active';
      case 2:
        return 'status-pending';
      case 3:
        return 'status-expired';
      default:
        return 'status-unknown';
    }
  },

  // 格式化日期
  formatDate(dateStr) {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`;
  },

  // 格式化时长
  formatDuration(hours) {
    if (!hours) return '0h';
    return `${hours}h`;
  },

  // 筛选事件
  handleFilter() {
    wx.showToast({
      title: '选择时间（后期扩展）',
      icon: 'none',
      duration: 2000
    });
  },

  // 跳转到访客详情页
  goToDetails(e) {
    const visitorId = e.currentTarget.dataset.id;
    
    wx.navigateTo({
      url: '/mine/pages/visitor-record/visitor-recordDetails/visitor-recordDetails?id=' + visitorId
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadVisitorRecords();
    wx.stopPullDownRefresh();
  }
})
    